<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手市场 - 首页</title>
    <style>
        :root {
            --primary-color: #4CAF50;
            --secondary-color: #66BB6A;
            --light-gray: #F5F5F5;
            --text-color: #212121;
            --sub-text: #757575;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--light-gray);
            min-height: 100vh;
            padding-bottom: 60px;
            position: relative;
        }

        .header {
            background-color: var(--primary-color);
            color: white;
            padding: 1rem;
            text-align: center;
        }

        .content {
            flex: 1;
        }

        .container {
            margin: 0 auto;
            padding: 1rem;
        }

        .search-box {
            display: flex;
            margin-bottom: 20px;
            gap: 10px;
        }

        .search-box input {
            flex: 1;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .search-box button {
            padding: 0.5rem 1rem;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-box button:hover {
            background-color: var(--secondary-color);
        }

        /* 轮播图样式 */
        .carousel-container {
            position: relative;
            margin: 20px auto;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .carousel-slide {
            display: flex;
            width: 100%;
            height: 200px;
            transition: transform 0.5s ease-in-out;
        }

        .carousel-item {
            min-width: 100%;
            height: 100%;
            position: relative;
        }

        .carousel-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .carousel-caption {
            position: absolute;
            bottom: 20px;
            left: 20px;
            right: 20px;
            color: white;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
        }

        .carousel-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0, 0, 0, 0.5);
            color: white;
            padding: 10px 15px;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
            z-index: 100;
        }

        .carousel-nav:hover {
            background: rgba(0, 0, 0, 0.8);
        }

        .prev {
            left: 0;
            border-radius: 0 4px 4px 0;
        }

        .next {
            right: 0;
            border-radius: 4px 0 0 4px;
        }

        .carousel-dots {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 5px;
            z-index: 100;
        }

        .carousel-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.5);
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }

        .carousel-dot.active {
            background: rgba(255, 255, 255, 0.9);
        }

        .hero {
            text-align: center;
            padding: 2rem 0;
            background-color: #fff;
            margin-bottom: 1rem;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .hero h2 {
            margin-bottom: 1rem;
        }

        .btn {
            display: inline-block;
            background-color: var(--primary-color);
            color: white;
            padding: 0.5rem 1rem;
            text-decoration: none;
            border-radius: 4px;
            margin-top: 1rem;
            transition: background-color 0.3s;
        }

        .btn:hover {
            background-color: var(--secondary-color);
        }

        .product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }

        .product-card {
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            padding: 1rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .product-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .product-card img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 0.5rem;
        }

        .product-card h3 {
            margin-bottom: 0.5rem;
            font-size: 1rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .product-card p {
            color: var(--sub-text);
            margin-bottom: 0.5rem;
            font-size: 0.8rem;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .product-card .price {
            font-weight: bold;
            color: #e74c3c;
            font-size: 1.1rem;
        }

        .product-card .date {
            font-size: 0.7rem;
            color: #95a5a6;
            margin-top: 0.3rem;
        }

        .nav-bar {
            display: flex;
            justify-content: space-around;
            background-color: #fff;
            padding: 0.5rem;
            position: fixed;
            bottom: 0;
            width: 100%;
            margin: 0 auto;
            left: 50%;
            transform: translateX(-50%);
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
            border-radius: 12px 12px 0 0;
            z-index: 102;
        }

        .nav-bar a {
            color: var(--sub-text);
            text-decoration: none;
            padding: 0.5rem 1rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 0.8rem;
            transition: color 0.3s;
            position: relative;
        }

        .nav-bar a.active {
            color: var(--primary-color);
        }

        .nav-bar a.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60%;
            height: 3px;
            background-color: var(--primary-color);
            border-radius: 3px;
        }

        .nav-icon {
            width: 24px;
            height: 24px;
            position: relative;
            margin-bottom: 0.2rem;
        }

        .home-icon::before {
            content: "🏠";
        }

        .products-icon::before {
            content: "📦";
        }

        .publish-icon::before {
            content: "✏️";
        }

        .news-icon::before {
            content: "💬";
        }

        .account-icon::before {
            content: "👤";
        }

        .new-badge {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: #e74c3c;
            color: white;
            font-size: 0.6rem;
            padding: 0.2rem 0.4rem;
            border-radius: 10px;
            line-height: 1;
        }
    </style>
</head>

<body>
    <header class="header">
        <h1>校园二手市场</h1>
    </header>

    <div class="content">
        <main class="container">
            <section class="search-box">
                <input type="text" id="searchInput" placeholder="请输入商品名称或关键词">
                <button onclick="filterProducts()">搜索</button>
                <button onclick="window.location.href='browse-history.html'">浏览历史</button>
            </section>

            <!-- 轮播图结构 -->
            <div class="carousel-container">
                <div class="carousel-slide">
                    <div class="carousel-item">
                        <img src="图片/1.jpg" alt="开学季大促">
                        <div class="carousel-caption">
                            <h2>开学季大促</h2>
                            <p>全场商品低至5折起！</p>
                        </div>
                    </div>
                    <div class="carousel-item">
                        <img src="图片/1.jpg" alt="毕业季特惠">
                        <div class="carousel-caption">
                            <h2>毕业季特惠</h2>
                            <p>学长学姐精选好物</p>
                        </div>
                    </div>
                    <div class="carousel-item">
                        <img src="图片/1.jpg" alt="电子产品专场">
                        <div class="carousel-caption">
                            <h2>电子产品专场</h2>
                            <p>限时特价，抢完即止</p>
                        </div>
                    </div>
                </div>
                <button class="carousel-nav prev">‹</button>
                <button class="carousel-nav next">›</button>
                <div class="carousel-dots"></div>
            </div>

            <section class="hero">
                <h2>欢迎来到校园二手市场</h2>
                <p>发现你需要的，转让你用过的</p>
                <a href="products.html" class="btn">浏览全部商品</a>
            </section>
            <section class="featured-products">
                <h3>最新商品</h3>
                <div id="featured-products-list" class="product-grid">
                    <!-- 推荐商品将通过JavaScript动态加载 -->
                </div>
            </section>
        </main>
    </div>

    <nav class="nav-bar">
        <a href="index.html" class="active">
            <div class="nav-icon home-icon"></div>
            首页
        </a>
        <a href="products.html">
            <div class="nav-icon products-icon"></div>
            商品
        </a>
        <a href="publish.html">
            <div class="nav-icon publish-icon"></div>
            发布
        </a>
        <a href="news.html">
            <div class="nav-icon news-icon"></div>
            消息
        </a>
        <a href="account.html">
            <div class="nav-icon account-icon"></div>
            我的
        </a>
    </nav>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const currentUser = JSON.parse(localStorage.getItem('currentUser'));
            if (!currentUser) {
                window.location.href = 'login.html';
            }

            // 初始化数据
            function initData() {
                let products = JSON.parse(localStorage.getItem('products'));

                if (!products || products.length === 0) {
                    products = [
                        { id: 1, title: '全新未拆封考研英语真题', description: '全新未拆封2023考研英语真题详解，包含近10年真题及详细解析。', price: 35, image: '图片/全新未拆封考研英语真题.jpg', category: '书籍', date: '2023-05-10', userId: 1, userName: '张同学' },
                        { id: 2, title: '九成新自行车', description: '九成新自行车，适合校园内使用。', price: 150, image: '图片/自行车.jpg', category: '交通工具', date: '2023-05-12', userId: 2, userName: '李同学' },
                        { id: 3, title: '电子书阅读器', description: '电子书阅读器，几乎全新，附带保护套。', price: 200, image: '图片/电子书阅读器.jpg', category: '电子产品', date: '2023-05-15', userId: 3, userName: '王同学' },
                        { id: 4, title: '宿舍用小冰箱', description: '宿舍用小冰箱，功能正常，适合存放饮料和零食。', price: 100, image: '图片/宿舍小冰箱.jpg', category: '家电', date: '2023-05-18', userId: 1, userName: '张同学' },
                        { id: 5, title: '宿舍用台灯', description: '宿舍用台灯，可调节亮度。', price: 30, image: '图片/宿舍用台灯.jpg', category: '生活', date: '2023-05-20', userId: 4, userName: '赵同学' },
                        { id: 6, title: '无线耳机', description: '无线蓝牙耳机，音质清晰，适合学习和娱乐。', price: 120, image: '图片/无线耳机.jpg', category: '电子产品', date: '2023-05-22', userId: 2, userName: '李同学' },
                        { id: 7, title: '折叠桌椅', description: '便携式折叠桌椅，适合户外活动和宿舍使用。', price: 80, image: '图片/折叠桌椅.jpg', category: '生活', date: '2023-05-25', userId: 5, userName: '刘同学' },
                        { id: 8, title: '背包', description: '多功能背包，适合日常使用和旅行。', price: 60, image: '图片/背包.jpg', category: '生活', date: '2023-05-28', userId: 3, userName: '王同学' },
                        { id: 9, title: '篮球', description: '标准篮球，适合校园篮球比赛和训练。', price: 45, image: '图片/篮球.jpg', category: '交通工具', date: '2023-06-01', userId: 4, userName: '赵同学' },
                        { id: 10, title: '笔记本电脑', description: '高性能笔记本电脑，适合学习和编程。', price: 2500, image: '图片/笔记本电脑.jpg', category: '电子产品', date: '2023-06-03', userId: 1, userName: '张同学' },
                        { id: 11, title: '智能手表', description: '智能手表，支持健康监测和通知提醒。', price: 180, image: '图片/智能手表.jpg', category: '电子产品', date: '2023-06-05', userId: 5, userName: '刘同学' },
                        { id: 12, title: '滑板', description: '初学者滑板，适合校园内短途出行。', price: 90, image: '图片/滑板.jpg', category: '交通工具', date: '2023-06-08', userId: 2, userName: '李同学' },
                        { id: 13, title: '水壶', description: '不锈钢水壶，保温效果好，适合日常使用。', price: 25, image: '图片/水壶.jpg', category: '生活', date: '2023-06-10', userId: 3, userName: '王同学' },
                        { id: 14, title: '绘画工具', description: '专业绘画工具，适合艺术学习和创作。', price: 75, image: '图片/绘画工具.jpg', category: '书籍', date: '2023-06-12', userId: 4, userName: '赵同学' },
                        { id: 15, title: '耳机支架', description: '耳机支架，帮助整理桌面空间。', price: 15, image: '图片/耳机支架.jpg', category: '生活', date: '2023-06-15', userId: 5, userName: '刘同学' }
                    ];
                    localStorage.setItem('products', JSON.stringify(products));
                }
            }

            initData();

            const featuredProductsList = document.getElementById('featured-products-list');
            let allProducts = JSON.parse(localStorage.getItem('products')) || [];
            allProducts.sort((a, b) => new Date(b.date) - new Date(a.date));

            // 搜索输入框回车事件
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('keydown', (event) => {
                if (event.key === 'Enter') {
                    filterProducts();
                }
            });

            // 渲染推荐商品列表
            function renderFeaturedProducts(list, products) {
                list.innerHTML = '';
                products.slice(0, 12).forEach(product => {
                    const productCard = document.createElement('div');
                    productCard.className = 'product-card';

                    const today = new Date();
                    const productDate = new Date(product.date);
                    const diffInHours = Math.floor((today - productDate) / (1000 * 60 * 60));

                    productCard.innerHTML = `
                        <img src="${product.image}" alt="${product.title}">
                        <h3>${product.title}</h3>
                        <p>${product.description}</p>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span class="price">¥${product.price}</span>
                            ${diffInHours <= 24 ? '<span class="new-badge">新</span>' : ''}
                        </div>
                        <p class="date">发布于: ${formatDate(product.date)}</p>
                    `;

                    productCard.addEventListener('click', function () {
                        addToBrowseHistory(product);
                        window.location.href = `product-detail.html?id=${product.id}`;
                    });
                    list.appendChild(productCard);
                });
            }

            // 格式化日期显示
            function formatDate(dateString) {
                const date = new Date(dateString);
                return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
            }

            // 初始化推荐商品列表
            renderFeaturedProducts(featuredProductsList, allProducts);

            // 根据关键词过滤商品
            function filterProducts() {
                const searchInput = document.getElementById('searchInput').value.toLowerCase();
                const filteredProducts = allProducts.filter(product => {
                    const productTitle = product.title.toLowerCase();
                    const productDescription = product.description.toLowerCase();
                    return productTitle.includes(searchInput) || productDescription.includes(searchInput);
                });

                renderFeaturedProducts(featuredProductsList, filteredProducts);
            }

            // 监听发布新商品后的数据更新
            window.addEventListener('productAdded', function () {
                allProducts = JSON.parse(localStorage.getItem('products')) || [];
                allProducts.sort((a, b) => new Date(b.date) - new Date(a.date));
                renderFeaturedProducts(featuredProductsList, allProducts);
            });

            // 轮播图逻辑
            const carouselSlide = document.querySelector('.carousel-slide');
            const carouselItems = document.querySelectorAll('.carousel-item');
            const prevButton = document.querySelector('.prev');
            const nextButton = document.querySelector('.next');
            const dotsContainer = document.querySelector('.carousel-dots');
            let currentIndex = 0;
            let autoPlayInterval;

            // 创建指示点
            carouselItems.forEach((_, index) => {
                const dot = document.createElement('button');
                dot.className = `carousel-dot ${index === 0 ? 'active' : ''}`;
                dot.addEventListener('click', () => goToSlide(index));
                dotsContainer.appendChild(dot);
            });

            // 自动播放
            function startAutoPlay() {
                autoPlayInterval = setInterval(() => goToSlide(currentIndex + 1), 5000);
            }

            // 停止自动播放
            function stopAutoPlay() {
                clearInterval(autoPlayInterval);
            }

            // 切换幻灯片
            function goToSlide(index) {
                currentIndex = (index + carouselItems.length) % carouselItems.length;
                carouselSlide.style.transform = `translateX(-${currentIndex * 100}%)`;

                document.querySelectorAll('.carousel-dot').forEach((dot, i) => {
                    dot.classList.toggle('active', i === currentIndex);
                });
            }

            // 事件监听
            prevButton.addEventListener('click', () => {
                goToSlide(currentIndex - 1);
                stopAutoPlay();
                startAutoPlay();
            });

            nextButton.addEventListener('click', () => {
                goToSlide(currentIndex + 1);
                stopAutoPlay();
                startAutoPlay();
            });

            // 鼠标悬停暂停
            carouselSlide.parentElement.addEventListener('mouseenter', stopAutoPlay);
            carouselSlide.parentElement.addEventListener('mouseleave', startAutoPlay);

            // 初始化自动播放
            startAutoPlay();

            // 浏览历史功能
            function addToBrowseHistory(product) {
                let browseHistory = JSON.parse(localStorage.getItem('browseHistory')) || [];

                const existingIndex = browseHistory.findIndex(p => p.id === product.id);
                if (existingIndex !== -1) {
                    browseHistory.splice(existingIndex, 1);
                }

                browseHistory.unshift(product);

                if (browseHistory.length > 10) {
                    browseHistory = browseHistory.slice(0, 10);
                }

                localStorage.setItem('browseHistory', JSON.stringify(browseHistory));
            }

            // 暴露搜索函数到全局
            window.filterProducts = filterProducts;
        });
    </script>
</body>

</html>